package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    KafkaTemplate kafkaTemplate;
    /**
     * 保存阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        if (dto==null ||dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry behaviorEntry=null;
        //登录时==查询行为实体
        if (user!=null && user.getId()!=null){
            behaviorEntry = apBehaviorEntryService
                    .findByUserIdOrEquipmentId(user.getId(), null);
        }
        //未登录时**查询行为实体
        behaviorEntry = apBehaviorEntryService
                .findByUserIdOrEquipmentId(null, 0);
        if (behaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApReadBehavior apReadBehavior = getOne(
                Wrappers.<ApReadBehavior>lambdaQuery()
                        .eq(ApReadBehavior::getEntryId, behaviorEntry.getId())
                        .eq(ApReadBehavior::getArticleId, dto.getArticleId())
        );

        //**** 文章阅读-发送消息
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setAdd(1);
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,
                UUID.randomUUID().toString(), JSON.toJSONString(mess));
        // ************************


        //无阅读行为时保存
        if (apReadBehavior==null){
            apReadBehavior = ApReadBehavior.builder()
                    .entryId(behaviorEntry.getId())
                    .articleId(dto.getArticleId())
                    .count(dto.getCount())
                    .percentage(dto.getPercentage())
                    .loadDuration(dto.getLoadDuration())
                    .readDuration(dto.getReadDuration())
                    .createdTime(new Date())
                    .build();
            save(apReadBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //更新阅读行为
        apReadBehavior.setCount((short)(apReadBehavior.getCount()+1));
        apReadBehavior.setUpdatedTime(new Date());
        updateById(apReadBehavior);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
